package com.htudata.core.util;

import java.io.IOException;
import java.net.URLDecoder;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class httpClientUtils {

  public static final int HTTP_STATUS_SUCCESS = 200;
  
  public static String sendPost(String url, String requestJson) throws Exception {
    if (url == null || url.trim().length() < 4)
      return null; 
    String result = "";
    try {
      RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build();
      CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
      RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
      HttpPost method = new HttpPost(url);
      method.setConfig(requestConfig);
      if (!StringUtils.isBlank(requestJson)) {
        StringEntity entity = new StringEntity(requestJson, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        method.setEntity((HttpEntity)entity);
      } 
      CloseableHttpResponse closeableHttpResponse = httpClient.execute((HttpUriRequest)method);
      url = URLDecoder.decode(url, "UTF-8");
      if (closeableHttpResponse.getStatusLine().getStatusCode() == 200)
        try {
          result = EntityUtils.toString(closeableHttpResponse.getEntity());
        } catch (Exception e) {
           throw e;
        }  
    } catch (IOException e) {

    } 
    return result;
  }
}
